package com.example.myproject.service.impl;

import com.example.myproject.exception.BusinessException;
import com.example.myproject.mapper.UserMapper;
import com.example.myproject.model.User;
import com.example.myproject.service.AvatarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class AvatarServiceImpl implements AvatarService {

    @Autowired
    private UserMapper userMapper;

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    @Value("${file.access.path:http://localhost:8080/uploads}")
    private String accessPath;

    @PostConstruct
    public void init() {
        try {
            // 创建上传目录
            Path uploadDir = Paths.get(uploadPath, "avatars");
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
        } catch (IOException e) {
            throw new RuntimeException("无法创建上传目录", e);
        }
    }

    @Override
    public String uploadAvatar(Long userId, MultipartFile file) {
        System.out.println("是否为空：" + file.isEmpty());
        System.out.println("原始文件名：" + file.getOriginalFilename());
        System.out.println("文件大小：" + file.getSize());

        // 校验类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new RuntimeException("只能上传图片文件");
        }

        // 校验大小（2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new RuntimeException("文件大小不能超过2MB");
        }

        String baseUploadPath = System.getProperty("user.dir") + "/avatars/";
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new IllegalArgumentException("上传文件名不能为空");
        }
        // 创建目录（如不存在）
        File uploadDir = new File(baseUploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            System.out.println("上传目录创建：" + created);
        }

        String uploadedFilePath = baseUploadPath + originalFilename;
        System.out.println("保存路径：" + uploadedFilePath);

        File uploadedFile = new File(uploadedFilePath);

        try {
            file.transferTo(uploadedFile);
        } catch (IOException e) {
            throw new BusinessException("保存图片文件失败");
        }


        // 构建 URL
        String newurl = "http://localhost:8080/avatars/" + originalFilename;

        // 更新用户头像
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + userId);
        }
        user.setAvatar(newurl);
        userMapper.updateById(user);

        // 返回 URL 给前端
        return newurl;
    }


    @Override
    public String getAvatarUrl(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user.getAvatar();
    }
}